using System;
using System.Collections.Generic;
using System.IO;
using SpoonCore.Handler;
using SpoonCore.Message.Info;
using SpoonCore.Message.Info.Core;

namespace SpoonCore.Message
{
	internal class JoinMessage : IMessage
	{
		private ClientInfo _joinClient;
		private JoinType _type = JoinType.Request;
		private List<ClientInfo> _clientList = new List<ClientInfo>();
		private MessageInfo _info = CoreInfoHandler.Confirmation;

		public enum JoinType : byte
		{
			Request,
			Response
		}

		public JoinMessage()
		{
		}

		public JoinMessage(ClientInfo joinClient)
		{
			_joinClient = joinClient;
		}


		public int MsgId
		{
			get { return 2; }
		}

		public ClientInfo JoinInfo
		{
			get { return _joinClient; }
			set { _joinClient = value; }
		}

		public JoinType Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public List<ClientInfo> Clients
		{
			get { return _clientList; }
			set { _clientList = value; }
		}

		public byte[] GetBytes()
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);

			bw.Write(_joinClient.GetBytes());
			bw.Write((byte)_type);
			if (_type == JoinType.Response)
			{
				bw.Write(_clientList.Count);
				foreach (ClientInfo info in _clientList)
				{
					bw.Write(info.GetBytes());
				}
			}

			return stream.ToArray();
		}

		public void SetBytes(SpoonClient client, BinaryReader br)
		{
			_joinClient = new ClientInfo(client, br);
			_type = (JoinType)br.ReadByte();
			if (_type == JoinType.Response)
			{
				int count = br.ReadInt32();
				while (count > 0)
				{
					_clientList.Add(new ClientInfo(client, br));
					count--;
				}
			}
		}

		public IMessage Clone()
		{
			return new JoinMessage();
		}

		public MessageInfo Info
		{
			get { return _info; }
			set { _info = value; }
		}
	}
}